package com.example.springboot.config.interceptors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * redis统计请求的次数
 *
 * @Author:ChenZhangKun
 * @Date: 2021/6/30 18:40
 */
@Component
public class RedisUrlCountInterceptor implements HandlerInterceptor {
    @Autowired
    protected StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        // 排除静态资源
        // ，默认每次访问当前的uri加1
        if (requestURI.contains("static") && requestURI.contains("assert")) {
            stringRedisTemplate.opsForValue().increment(requestURI);
        }
        return true;
    }
}
